from django.shortcuts import render
from django.views import View
from django import http
from django.contrib.auth import login, logout, authenticate
from django_redis import get_redis_connection
from meiduo_mail.utils.views import LoginRequireJSONMixin, LoginRequiredTestMixin
from celery_tasks.email.tasks import send_verify_email
from apps.users.utils import generate_email_verify_url, check_email_verify_url
from apps.goods.models import SKU
from apps.users.serializer import UserSerializer

import logging, json, re

from apps.users.models import User, Address
# Create your views here.


# 创建日志输出器
logger = logging.getLogger('django')


class UserBrowseHistory(LoginRequireJSONMixin, View):
    """用户浏览记录:
    POST:/browse_histories/
    """
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoseNotExist:
            return http.JsonResponse({'code': 400, 'errmsg': "sku_id不存在"})

        user_id = request.user.id
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()
        # 去重
        pl.lrem('history_%s' % user_id, 0, sku_id)
        # 添加
        pl.lpush('history_%s' % user_id, sku_id)
        # 截取
        pl.ltrim('history_%s' % user_id, 0, 4)

        pl.execute()

        return http.JsonResponse({'code': 400, 'errmsg':'ok'})

    def get(self, request):
        user_id = request.user.id
        redis_conn = get_redis_connection('history')
        sku_ids = redis_conn.lrange('history_%s' % user_id, 0, -1)
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                "id": sku.id,
                "name": sku.name,
                "default_image_url": sku.default_image.url,
                "price": sku.price
            })
        return http.JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'skus': skus
        })


class UserNameCountView(View):
    """判断用户名是否重复注册
    GET http://www.meiduo.site:8000/usernames/itcast/count/
    """
    def get(self,request, username):
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '数据错误'})

        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    """判断用户名是否重复注册
    GET http://www.meiduo.site:8000/mobile/15911520667/count/
    """
    def get(self,request, mobile):
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '数据错误'})

        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class RegisterView(View):

    def post(self, request):
        # json_bytes = request.body
        # json_str = json_bytes.decode()
        # json_dict = json.loads(json_str)
        json_dict = json.loads(request.body.decode())
        #
        # # 获取前端用户输入
        # username = json_dict.get("username")
        # password = json_dict.get("password")
        # password2 = json_dict.get("password")
        # mobile = json_dict.get("mobile")
        # sms_code_client = json_dict.get("sms_code")
        # allow = json_dict.get("allow")
        #
        # if not all([username, password, password2, mobile, sms_code_client, allow]):
        #     return http.JsonResponse({'code': 400, 'errmsg': '缺少必填参数'})
        #
        # if not re.match(r'^[0-9a-zA-Z_-]{5,20}$', username):
        #     return http.JsonResponse({'code': 400, 'errmsg': '参数username有误'})
        #
        # if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
        #     return http.JsonResponse({'code': 400, 'errmsg': '参数password有误'})
        #
        # if password != password2:
        #     return http.JsonResponse({'code': 400, 'errmsg': '密码两次输入不一致'})
        #
        # if not re.match(r'^1[3-9]\d{9}$',mobile):
        #     return http.JsonResponse({'code': 400, 'errmsg': '手机号码输入有误'})
        #
        # if allow != True:
        #     return http.JsonResponse({'code': 400, 'errmsg': 'allow参数有误'})
        #
        # redis_conn = get_redis_connection('verify_code')
        # sms_code_server = redis_conn.get('sms%s' % mobile)
        # # 短信验证码校验1：是否已经过期
        # if not sms_code_server:
        #     return http.JsonResponse({'code': 400, 'errmsg': '短信验证码过期'})
        # # 短信验证码校验2：输入是否正确
        # if sms_code_client != sms_code_server.decode():
        #     return http.JsonResponse({'code': 400, 'errmsg': '短信验证错误'})
        #
        # # 用户注册信息写入数据库
        # try:
        #     user = User.objects.create_user(username=username, password=password, mobile=mobile)
        # except Exception as e:
        #     logger.error(e)
        #     return http.JsonResponse({'code': 400, 'errmsg': '注册失败'})
        serializer = UserSerializer(data=json_dict)
        serializer.is_valid()
        user = serializer.save()
        # 实现状态保持
        login(request, user)

        response = http.JsonResponse({'code': 0, 'errmsg': '注册成功'})
        response.set_cookie('username', user.username, max_age=14 * 24 * 3600)

        return response


class LoginView(View):

    def post(self, request):
        # 获取用户名密码等参数
        # json_byte = request.body
        # json_str = json_byte.decode()
        # json_dict = json.loads(json_str)
        json_dict = json.loads(request.body.decode())

        account = json_dict.get("username")
        password = json_dict.get("password")
        remembered = json_dict.get("remembered")

        if not all([account, password]):
            return http.JsonResponse({'code': 400, 'errmsg': "缺少必传参数"})

        if re.match(r'^1[3-9]\d{9}$', account):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        user = authenticate(request=request,
                            username=account,
                            password=password)

        if user is None:
            return http.JsonResponse({'code': 400, 'errmsg': "用户名或密码错误"})

        login(request, user)

        if remembered:
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)

        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age=14*24*3600)

        from apps.carts.utils import merge_cart_cookie_to_redis
        merge_cart_cookie_to_redis(request, user, response)

        return response


class LogoutView(View):

    def delete(self, request):
        # 1、清理session
        logout(request)
        response = http.JsonResponse({'code':0, 'errmsg':'ok'})
        # 2、清理cookie
        response.delete_cookie('username')
        return response


class UserInfoView(LoginRequireJSONMixin, View):
    """用户中心"""
    def get(self, request):
        # 判断用户是否登录
        # if not request.user.is_authenticated:
        #     return http.JsonResponse({"code": 400, "errmag": "用户未登录"})
        serializer = UserSerializer(request.user)
        data_dict = {
            "code":0,
            "errmsg":"ok",
            "info_data": serializer.data
            # "info_data": {
            #     "username": request.user.username,
            #     "mobile": request.user.mobile,
            #     "email": request.user.email,
            #     "email_active": request.user.email_active
            # }
        }
        return http.JsonResponse(data_dict)


class EmailView(LoginRequireJSONMixin, View):

    def put(self, request):
        json_dict = json.loads(request.body.decode())
        email = json_dict.get("email")

        if not email:
            return http.JsonResponse({'code':400, 'errmsg': '缺少必传参数'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return http.JsonResponse({'code': 400, 'errmsg': '邮箱格式错误'})

        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':400, 'errmsg': '数据库添加数据错误'})
        verify_url = generate_email_verify_url(request.user)
        send_verify_email.delay(email, verify_url)

        return http.JsonResponse({'code':0, 'errmsg': 'ok'})


class EmailActiveView(View):

    def put(self, request):
        token = request.GET.get('token')
        if not token:
            return http.JsonResponse({'code':400, 'errmsg': '缺少必填参数'})

        user = check_email_verify_url(token)
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code':400, 'errmsg': '邮箱验证失败'})
        return http.JsonResponse({'code':0, 'errmsg': '邮箱验证成功'})


class CreateAddressView(LoginRequireJSONMixin, View):
    def post(self, request):
        count = request.user.addresses.filter(is_delete=False).count()
        if count >= 20:
            return http.JsonResponse({'code': 400, 'errmsg': '地址数量超过上限'})

        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')  # 非必传
        email = json_dict.get('email')  # 非必传

        # province_id,city_id,district_id由于是外键带过来的，不用再进行校验
        if not all([receiver, place, mobile]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}', mobile):
            return http.JsonResponse({'code':400, 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return http.JsonResponse({'code': 400, 'errmsg': '参数tel有误'})

        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return http.JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        try:
            address = Address.objects.create(
                user=request.user,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                title=receiver,
                receiver=receiver,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email,
            )

            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '新增地址失败'})

        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province': address.province.name,
            'city': address.city.name,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email
        }
        return http.JsonResponse({'code': 0, 'errmsg': 'OK', 'address': address_dict})


class AddressView(LoginRequireJSONMixin, View):
    def get(self, request):
        address_model_list = request.user.addresses.filter(is_delete=False)
        address_dict_list = []
        for address in address_model_list:
            address_dict = {
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            }
            address_dict_list.append(address_dict)

        default_address_id = request.user.default_address_id
        return http.JsonResponse({
            "code": 0,
            "errmsg": "ok",
            "default_address_id": default_address_id,
            "addresses": address_dict_list
        })



